package com.example.controller;

import com.example.service.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 元数据管理控制器
 */
@RestController
@RequestMapping("/api/metadata")
public class MetadataController {

    @Autowired
    private MetadataService metadataService;

    /**
     * 手动刷新默认数据库元数据
     */
    @PostMapping("/refresh/default")
    public ResponseEntity<?> refreshDefaultMetadata(@RequestAttribute Long userId) {
        try {
            metadataService.refreshDefaultSchemaMetadata();
            Map<String, String> response = new HashMap<>();
            response.put("message", "默认数据库元数据刷新已启动");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "刷新元数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 清除指定数据库连接的元数据缓存
     */
    @PostMapping("/clear/{connectionId}")
    public ResponseEntity<?> clearConnectionMetadata(
            @PathVariable Long connectionId,
            @RequestAttribute Long userId
    ) {
        try {
            metadataService.clearSchemaCache(connectionId);
            Map<String, String> response = new HashMap<>();
            response.put("message", "数据库连接元数据缓存已清除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "清除元数据缓存失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
} 